package com.example.wwk.graduationpractice.Activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.example.wwk.graduationpractice.Bean.AnswerBean;
import com.example.wwk.graduationpractice.Bean.QuestionBean;
import com.example.wwk.graduationpractice.Globalutils.ActivityCollector;
import com.example.wwk.graduationpractice.Globalutils.MyApplication;
import com.example.wwk.graduationpractice.Globalutils.PromptShowUtils;
import com.example.wwk.graduationpractice.Globalutils.SharedPreferenceUtils;
import com.example.wwk.graduationpractice.Globalutils.TimeUtils;
import com.example.wwk.graduationpractice.R;

import org.jivesoftware.smack.AbstractXMPPConnection;
import org.jivesoftware.smack.SmackException;
import org.jivesoftware.smack.chat.Chat;
import org.jivesoftware.smack.chat.ChatManager;

public class ReplyActivity extends AppCompatActivity implements View.OnClickListener {
    //back
    private ImageView back;
    //记住回答的草稿
    private SharedPreferences pref;
    private SharedPreferences.Editor editor;
    private String answer;        //评答文稿
    //edit
    private EditText input;
    //intent的传值
    private String thisUser;
    private String questionid;
    //button发表
    private Button publish;

    //smack 建立消息通道
    private AbstractXMPPConnection connection;
    private static ChatManager chatManager;
    private static Chat chat;
    //回答内容的接收者
    private static final String answerReceiver = "answer";
    //log tag
    private String TAG = "123";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.reply_activity);
        setTitle("");
        ActivityCollector.addActivity(this);
        //intent
        Intent intent = getIntent();
        thisUser = intent.getStringExtra("thisuserName");        //获取当前用户的用户名
        questionid = intent.getStringExtra("questionid");
        Log.d(TAG, "onCreate: questionid" + questionid);
        //input
        input = (EditText) findViewById(R.id.input);
        //SharedPreferences
        pref = SharedPreferenceUtils.getSharedPreferences();
        editor = SharedPreferenceUtils.getSharedEditor();
        getAnswer();      //获得之前保存的问题草稿
        //back
        back = (ImageView) findViewById(R.id.back);
        back.setOnClickListener(this);
        //toolbar
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        //button publish
        publish = (Button) findViewById(R.id.publish);
        publish.setOnClickListener(this);
        //connection
        connection = MyApplication.getConnection();//全局连接
        chatManager = ChatManager.getInstanceFor(connection);      //获取实例
        chat = chatManager.createChat(answerReceiver + "@" + connection.getServiceName());   //为发送信息(回答)建立聊天通道
    }

    /*
    * 获得之前回答的草稿
    */
    private void getAnswer() {
        String user = pref.getString("thisUser", "");
        if (user != null) {
            if (thisUser.equals(user)) {
                answer = pref.getString("answer", "");
                if (answer != null && !answer.equals("")) {
                    input.setText(answer);
                }
            }
        }
    }

    /*
    * 对话框，是否保存草稿
    * @param String answer
    * @param Context context
    * return boolean
    */
    public boolean showDialog(final String answer, Context context) {
        MaterialDialog materialDialog;
        materialDialog = new MaterialDialog.Builder(context)
                .title("提示")
                .content("是否保存草稿？")
                .positiveText("保存")
                .negativeText("不保存")
                .onAny(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        if (which == DialogAction.POSITIVE) {
                            editor.putString("thisUser", thisUser);
                            editor.putString("answer", answer);  //保存输入的草稿
                            editor.apply();
                            finish();
                        } else if (which == DialogAction.NEGATIVE) {    //不保存
                            editor.putString("thisUser", thisUser);
                            editor.putString("answer", "");
                            editor.apply();
                            finish();
                        }
                    }

                })
                .show();

        if (materialDialog.isCancelled())
            return true;
        else
            return false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ActivityCollector.removeActivity(this);

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back:
                //finish前的对话框
                answer = input.getText().toString();
                boolean flag;
                if (!answer.equals("")) {//输入内容不为空
                    flag = showDialog(answer, ReplyActivity.this);
                } else
                    flag = true;
                if (flag)
                    finish();
                break;
            case R.id.publish:
                //发表回答时清空保存的草稿
                editor.putString("user", thisUser);
                editor.putString("answer", "");
                editor.apply();
                answer = input.getText().toString();
                //  回答不为空
                if (!"".equals(answer)) {
                    AnswerBean answerBean = returnResult(questionid, thisUser, answer);   //将发表的回答返回给answerActivity，用于显示
                    Intent intent = new Intent();
                    intent.putExtra("answerBean", answerBean);
                    setResult(RESULT_OK, intent);       //返回结果给上一个页面，用于显示
                    answer = questionid + "#" + answer;
                    answerSend(answer, chat);        //将发表的回答发送给openfire
                    finish();
                } else {
                    PromptShowUtils.showToast("回答不能为空！");
                }
                break;
        }
    }

    /*返回的回答内容结果
    * @param String questionid
    * @param String thisUser
    * @param String answer
    * return AnswerBean
    */
    private AnswerBean returnResult(String questionid, String thisUser, String answer) {
        String time = TimeUtils.getTime();
        int questionId = Integer.parseInt(questionid);
        AnswerBean answerBean = new AnswerBean(questionId, thisUser, time, answer);
        return answerBean;
    }

    /*
    发送回答内容
    */
    private void answerSend(String answer, Chat chat) {
        try {
            chat.sendMessage(answer);
        } catch (SmackException.NotConnectedException e) {
            e.printStackTrace();
            PromptShowUtils.showToast("添加回答失败！");
        }
    }
}
